﻿using System;
using System.Diagnostics;

namespace Engine.Utils
{
    /// <summary>
    /// 单例模板
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Singleton<T> where T : IInit, IDispose, new()
    {
        protected static T _instance = default(T);
        private static Object _objLock = new System.Object();

        protected Singleton()
        {
            Debug.Assert(_instance == null);
        }

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_objLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                            // 手动调用，如果定义即调用的话，在有I/O操作的情况下会产生无法控制的先后问题。
                            // _instance.Init();
                        }
                    }
                }
                return _instance;
            }
        }

        public static bool DestroyInstance()
        {
            bool result = false;
            if (_instance != null)
            {
                _instance.Dispose();
                result = true;
            }

            _instance = default(T);
            return result;
        }
    }

    public interface IInit
    {
        void Init();
    }

    public interface IDispose
    {
        void Dispose();
    }
}